/*
 * FfmpegMediaReader.h
 *
 *  Created on: 2017年3月15日
 *      Author: chuanjiang.zh
 */

#ifndef FFMPEG_MEDIAREADER_H_
#define FFMPEG_MEDIAREADER_H_

#include "UMediaReader.h"
#include "TCriticalSection.h"
#include <string>
#include "Ffmpeg.h"


class FfmpegMediaReader: public UMediaReader
{
public:
	FfmpegMediaReader();
	virtual ~FfmpegMediaReader();

	virtual int open(const char* url, const char* params);

	virtual void close();

	virtual bool isOpen();

	virtual bool getFormat(UMediaFormat& fmt);

    virtual int getDuration();

	virtual bool play();
	virtual bool pause();
	virtual void stop();

	virtual int getState();

	virtual bool seekable();

	virtual bool seek(int64_t offset);

	virtual int64_t getTime();

	virtual bool setScale(float scale);

	virtual float getScale();

	virtual int read(UMediaPacket& pkt);

    virtual void interrupt();

    virtual bool isLive();

	virtual const char* getFormatName();

	virtual size_t getMetaData(const char* name, char* value, size_t size);


    int checkInterrupt();

    void customAudioTs(bool enabled);


protected:
    int openInput(const std::string& url, const std::string& params);
    void closeInput();
    bool isInputOpen();

    void fetchMediaFormat();

    void setState(UMediaState state);

    int parseParams(AVDictionary **pm, const std::string& params);

    int doRead(AVPacket& pkt);

    bool isFile();

	bool needTransformNalu();

    void onOpen(AVFormatContext* fmtContext);

	void openFilter();
	void closeFilter();

    bool convert(AVPacket& pkt);

    void customAudioTs(AVPacket& pkt);

    int read(AVPacket& pkt);

protected:
	std::string	m_url;
	std::string	m_params;
	AVDictionary* m_dict;
	AVFormatContext* m_fmtContext;
	
	int m_videoIdx;
	int m_audioIdx;
	UMediaFormat	m_format;
	int	m_hasBFrame;

	UMediaState		m_state;
	comn::CriticalSection	m_cs;
    int m_interrupted;
    bool 	m_paused;
    bool  	m_isFile;
    int64_t	m_curTime;

	bool m_transformNalu;
    AVBitStreamFilterContext* m_bsfc;

    std::string m_vprop;

    bool    m_audioTsCustomed;
    int64_t m_audioTs;

	std::string	m_fmtName;

};




#endif /* FFMPEG_MEDIAREADER_H_ */
